package com.qingdai.securityauth.impl;


import com.qingdai.business.emuns.User;
import com.qingdai.business.service.UserService;
import com.qingdai.business.utils.AuthoritiesUtil;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private AuthoritiesUtil authoritiesUtil;
    @DubboReference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            //只有在抛出异常时才认定为登录失败
            throw new UsernameNotFoundException("用户不存在");
        }

//          定义一个字符串泛型的List集合对象
        List<String> authorities = authoritiesUtil.getAuthoritiesByUserId(user.getId());

        /*
         * 如果 loadUserByUsername未抛出异常，则校验返回值中保存的密码和请求参数密码是否匹配。
         * 获取spring容器中的PasswordEncoder类型对象，调用方法matches比较密码。
         * 如果密码比较结果是true，登录成功。
         * 如果密码比较结果是false，登录失败，重定向到/login?error。
         */
        org.springframework.security.core.userdetails.User result =
                new org.springframework.security.core.userdetails.User(
                        username, //用户名
                        user.getPassword(), //登录用户的密码，是服务端保存到密文
                        AuthorityUtils.createAuthorityList(String.valueOf(authorities))//通过工具，把字符串权限转换成Security定义的权限

                );


        return result;
//        return new LoginUser(user);
    }

}

